import { computed, onUnmounted, ref } from 'vue'
import dayjs from 'dayjs'

// 封装倒计时逻辑函数
export const useCountDown = () => {
  let timer = null
  // 响应式数据， 开启倒计时的函数
  const time = ref(0)
  // 格式化时间为xx分xx秒
  const formatTime = computed(() => dayjs.unix(time.value).format('mm分ss秒'))
  const start = (currentTime) => {
    time.value = currentTime
    // 开启倒计时的逻辑
    timer = setInterval(() => {
      time.value--
    }, 1000)
  }
  // 组件销毁时清除定时器
  onUnmounted(() => {
    timer && clearTimeout(timer)
  })
  return {
    formatTime,
    start
  }
}